package club.zhcs.capture.qiniu;

import java.io.File;

import org.nutz.lang.Files;
import org.nutz.lang.random.R;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

public class GJUploader {

	private static Auth auth = Auth.create("-iwjFre8bIid-UQLcwoQExyCRxylPw2oSZ7XiZDr", "ijC6Bn-75M0NJh0yhDLZZcR5iQt5rQekRsOcgC6H");
	static UploadManager uploadManager = new UploadManager();

	/**
	 * 上传文件
	 * 
	 * @param path
	 *            文件路径
	 * @param fileName
	 *            文件名称,建议用UUID生成
	 * @return 七牛文件key 将此key存入本地数据库 使用时可通过
	 *         http://7xl7yg.com1.z0.glb.clouddn.com/${key}访问文件
	 */
	public static String upload(String path, String fileName) {
		try {
			Response res = uploadManager.put(new File(path), fileName, getUpToken());
			if (res.isOK()) {
				return fileName;
			} else {
			}
		} catch (QiniuException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 上传文件
	 * 
	 * @param path
	 *            文件路径
	 * @return 七牛文件key 将此key存入本地数据库 使用时可通过
	 *         http://7xl7yg.com1.z0.glb.clouddn.com/${key}访问文件,此处的key为自动生成
	 */
	public static String upload(String path) {
		return upload(path, getFileName(path));
	}

	/**
	 * 
	 * @param file
	 * @return
	 */
	public static String upload(File file) {
		return upload(file.getPath());
	}

	/**
	 * 获取文件名
	 * 
	 * @param path
	 *            文件路径
	 * @return
	 */
	private static String getFileName(String path) {
		return R.UU16() + "." + Files.getSuffixName(new File(path));
	}

	private static final String QINIU = "http://7xn1k1.com1.z0.glb.clouddn.com/";

	public static String getUrl(String key) {
		return auth.privateDownloadUrl(QINIU + key);
	}

	/**
	 * 获取上传token 非请勿动
	 * 
	 * @return
	 */
	private static String getUpToken() {
		return auth.uploadToken("gaojiancorp", null, 3600,
				new StringMap().putNotEmpty("returnBody", "{\"key\": $(key), \"hash\": $(etag), \"width\": $(imageInfo.width), \"height\": $(imageInfo.height)}"));
	}
}
